package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FlexiGridServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		JdbcUtil db = JdbcUtil.getInstance();

		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		String sql = "";
		// 当前第几页
		String pageIndex = request.getParameter("page");
		// 每页多少条
		String pageSize = request.getParameter("rp");
		// 条件字段值ֵ
		String query = new String(request.getParameter("query").getBytes("ISO8859-1"), "UTF-8");
		// 条件字段
		String qtype = request.getParameter("qtype");
		// 排序字段
		String sortname = request.getParameter("sortname");
		// desc or asc
		String sortorder = request.getParameter("sortorder");
		// 操作符
		String qop = request.getParameter("qop");
		int count = 0;
		List list = null;
		try {
			sql = "select count(*) from job_info1";
			if (!query.equals("")) {
				sql += " where " + qtype + " like " + "'%" + query + "%'";
			}
			count = db.executeQuery(sql);
			sql = "select * from job_info1";
			if (!query.equals("")) {
				sql += " where " + qtype + " like " + "'%" + query + "%'";
			}
			sql += " order by " + sortname + " " + sortorder;
			sql += " limit " + ((Integer.parseInt(pageIndex) - 1) * Integer.parseInt(pageSize)) + "," + pageSize;
			list = db.executeQueryList(sql);
			if (list == null) {
				System.out.println("======出错啦======");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<>();
		map.put("page", pageIndex);
		map.put("total", count);
		map.put("rows", list);
		// to JSON
		String json = com.alibaba.fastjson.JSON.toJSONString(map);
		System.out.println(json);
		response.getWriter().write(json);
		response.getWriter().flush();
		response.getWriter().close();
	}

}
